package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    /*
        下单
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("订单提交成功");
    }

    /*
        历史订单
     */
    @GetMapping("/userPage")
    public R<Page> history(int page, int pageSize){
        //分页构造器
        Page<Orders> orderPage = new Page<>();
        Page<OrdersDto> dtoPage = new Page<>();
        //查询对象
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //不需要分页，一页显示
        //日期排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        this.orderService.page(orderPage,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(orderPage,dtoPage);

        //通过orderId查询对应Detail
        LambdaQueryWrapper<OrderDetail> queryWrapper2 = new LambdaQueryWrapper<>();

        List<Orders> records = orderPage.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            //对象拷贝
            BeanUtils.copyProperties(item,ordersDto);
            //获取订单id
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            //赋值
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());

        BeanUtils.copyProperties(orderPage,dtoPage,"records");
        dtoPage.setRecords(ordersDtoList);
        return R.success(dtoPage);
    }

    /*
     * 再来一单
     */
    @PostMapping("/again")
    public R<String> againSubmit(@RequestBody Map<String,String> map){
        String ids = map.get("id");
        long id = Long.parseLong(ids);
//        log.info(String.valueOf(map));

        //查询当前订单
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        Long currentId = BaseContext.getCurrentId();
        //清空当前用户的购物车
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,currentId);
        shoppingCartService.remove(wrapper);


        //重新为购物车添加商品
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item)->{
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item,shoppingCart);
            shoppingCart.setUserId(currentId);
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            String dishFlavor = item.getDishFlavor();
            if(dishId != null){
                shoppingCart.setDishId(dishId);
                shoppingCart.setDishFlavor(dishFlavor);
            }else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
        return R.success("再来一单成功");
    }


    /*
        后台订单明细
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number,@DateTimeFormat String beginTime,@DateTimeFormat String endTime){
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        log.info(String.valueOf(pageInfo));

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //根据number查询
        queryWrapper.like(number != null,Orders::getNumber,number);
        //再根据时间查询
        if(beginTime != null && endTime != null){
            queryWrapper.ge(Orders::getOrderTime,beginTime);
            queryWrapper.le(Orders::getOrderTime,endTime);
        }
        //添加排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //查询
        orderService.page(pageInfo,queryWrapper);

        //为pageInfo添加用户姓名
        List<Orders> records = pageInfo.getRecords();

        List<Orders> list = records.stream().map((item) -> {
            String userName = item.getConsignee();
            Orders orders = new Orders();
            BeanUtils.copyProperties(item,orders);
            orders.setUserName(userName);
            return orders;
        }).collect(Collectors.toList());

        pageInfo.setRecords(list);

        return R.success(pageInfo);


    }

    /*
        订单派送
     */
    @PutMapping
    public R<String> send(@RequestBody Orders orders){
        Long id = orders.getId();
        Integer status = orders.getStatus();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,id);
        Orders one = orderService.getOne(queryWrapper);
        one.setStatus(status);
        orderService.updateById(one);

        return R.success("派送成功");
    }
}
